package com.xc.freeapp.util;

import java.util.HashMap;
import java.util.Set;

import org.apache.log4j.Logger;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.xc.freeapp.exception.BaseException;

public class SendSMSUtil {
	private static Logger log = Logger.getLogger(SendSMSUtil.class.getClass());
	private static String accountSid =PropertiesUtil.setFile("sms").getString("accountSid");//登录账号
    private static String accountToken =PropertiesUtil.setFile("sms").getString("accountToken");//登录密码
    
    private static String Appid =PropertiesUtil.setFile("sms").getString("Appid");//Appid
	public static CCPRestSDK restAPI;
	static{
		restAPI = new CCPRestSDK();
		restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
		restAPI.setAccount(accountSid, accountToken);// 初始化主帐号和主帐号TOKEN
		restAPI.setAppId(Appid);// 初始化应用ID
	}
	public static void main(String [] args){
//		try {
//			sendCode("15821470037","123123","5");
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
	}
	
	public static boolean sendCode(String phoneNo,String [] verificationCode,String templateid) throws Exception{
		boolean resultStatus=false;
		try {
			log.debug("accountSid="+accountSid+";accountToken="+accountToken+";Appid="+Appid);
			log.info(phoneNo+"调用接口发送验证码开始");
			HashMap<String, Object> result = null;
			result = restAPI.sendTemplateSMS(phoneNo,templateid ,verificationCode);
			log.info(phoneNo+"调用发送短信接口返回:"+result);
			if("000000".equals(result.get("statusCode"))){
				//正常返回输出data包体信息（map）
				HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
				Set<String> keySet = data.keySet();
				log.info(phoneNo+"调用发送短信接口成功:"+data);
				resultStatus = true;
			}else{
				//异常返回输出错误码和错误信息
				log.error(phoneNo+"：调用发送短信验证码接口出错，错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
				if("160038".equals(result.get("statusCode").toString())){
					throw new BaseException(Constant.ERRORCODE_445, result.get("statusMsg").toString());
				}else if("160040".equals(result.get("statusCode").toString())){
					throw new BaseException(Constant.ERRORCODE_446, result.get("statusMsg").toString());
				}else{
					throw new BaseException(Constant.GLOBAL_ERROR, result.get("statusMsg").toString());
				}
				
			}
		} catch(BaseException e){
			throw e;
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(phoneNo+"：调用发送短信验证码接口出错"+e);
			throw new BaseException("PA9999", "发送短信验证码出错");
		}
		return resultStatus;
	}
}
